
import java.net.*;
import java.io.*;


public class MainServer {

    String Filename;
    String New_Dir;
    String Filename_search;
    int FileSize;
    int PieceSize;
    int Num_of_pieces; 

    String Read_File_Parts = "" ;
    String clientSentence;
    String CapitalizedSentence;
    String ServerID = peerProcess.currentPeerId;
    int PORT_NO = 6010;
    String Header = "" ;
    String Headercheck;
    String PeerIDcheck;
    ServerSocket welcomeSocket = null;
    static String Bitfield = new String();

    public MainServer(boolean isFilePresent) {
        //Filename = Common_cfg.FileName;
    	Filename = peerProcess.Common_cfg.fileName;
    	New_Dir = "" ;
        Filename_search = "";
        //FileSize = Common_cfg.FileSize;
        FileSize = peerProcess.Common_cfg.fileSize;
        //PieceSize = Common_cfg.PieceSize;
        PieceSize = peerProcess.Common_cfg.pieceSize;
        Num_of_pieces = peerProcess.no_of_pieces;

        Bitfield = "";

        boolean success = (new File(New_Dir)).mkdir();
        if (success) {
            System.out.println("Directory created");
        }

        if (isFilePresent) {
            SplitFile();
            for (int i = 0; i < Num_of_pieces; i++) {
                Bitfield += "1";
            }
        } else {
            for (int i = 0; i < Num_of_pieces; i++) {
                Bitfield += "0";
            }
        }

    }

    public void SplitFile() {

        try {
            FileInputStream fis = new FileInputStream(Filename);
            int size = PieceSize;

            byte buffer[] = new byte[size];

            int count = 0;
            while (true) {
                int i = fis.read(buffer, 0, size);
                if (i == -1) {
                    break;
                }
                String filename = Filename_search + count;
                FileOutputStream fos;

                count++;
                
                fos = new FileOutputStream(filename);
                fos.write(buffer, 0, i);

                fos.flush();
                fos.close();
            }


        } catch (Exception oe) {
        }

    }

    public ServerSocket Server() {

        try {
            welcomeSocket = new ServerSocket(PORT_NO);            
     
        } catch (Exception ex) {
        	ex.printStackTrace();
        }

        return welcomeSocket;
    }
}
